package com.zone.core.base.adapter

import androidx.databinding.ObservableInt
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2

class SimpleFragmentAdapter<T>(
    viewPager: ViewPager2,
    fragmentManager: FragmentManager,
    lifecycle: Lifecycle
) : FragmentStateAdapter(fragmentManager, lifecycle) {

    lateinit var fragments: List<T>
    var itemChangeListener: OnItemChangeListener<T>? = null
    var selectPosition: ObservableInt? = null

    init {
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                itemChangeListener?.onItemClick(fragments[position], position)
            }
        })

        selectPosition?.notifyChange()
    }

    override fun createFragment(position: Int): Fragment {
        return fragments[position] as Fragment
    }

    override fun getItemCount(): Int {
        return fragments.size
    }

    interface OnItemChangeListener<T> {
        fun onItemClick(t: T?, position: Int)
    }
}